from typing import List, Optional, Tuple
from app.utils.request import RequestHandler
from app.core.crud import CRUDBase
from app.models.system.aiprojects import AIProject
from app.schemas.system.aiprojects import AIProjectCreate, AIProjectUpdate
from app.services.system.aiprojects import aiprojects_service
from app.schemas.base.error_code import *
from app.core.exceptions import BusinessError
from app.utils.app_log import logger
from tortoise.expressions import Q

class AIProjectController():
    async def project_list(self, page: int, page_size: int, q: Q) -> Tuple[int, List[dict]]:
        """获取AI项目列表"""
        try:
            total, project_objs = await aiprojects_service.list(page=page, page_size=page_size, search=q)
            data = [await obj.to_dict() for obj in project_objs]
            return total, data
        except Exception as e:
            raise BusinessError(RESOURCE_ACCESS_DENIED, details=f"获取AI项目列表出错：{str(e)}")

    async def get_project_info(self, project_id: int, user_id: int) -> dict:
        """获取AI项目详情"""
        try:
            project_obj = await aiprojects_service.get_project_by_user(project_id, user_id)
            if not project_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="AI项目"), details="项目不存在")
            project_dict = await project_obj.to_dict()
            # logger.info(f"获取AI项目详情: {project_dict}")
            if project_obj.user:
                project_dict['username'] = project_obj.user.username
            return project_dict
        except Exception as e:
            raise BusinessError(RESOURCE_NOT_FOUND.format(resource="AI项目"), details=f"项目不存在：{str(e)}")

    async def remove_project(self, project_id: int, user_id: int) -> bool:
        """删除AI项目"""
        try:
            project_obj = await aiprojects_service.get_project_by_user(project_id, user_id)
            if not project_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="AI项目"), details="项目不存在")
            await aiprojects_service.remove(project_id)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_DELETE_FAILED.format(resource="AI项目"), details=f"删除AI项目失败 {str(e)}")

    async def create_project(self, project_in: AIProjectCreate) -> AIProject:
        """创建AI项目"""
        try:
            # 检查同名项目是否已存在
            existing_project = await aiprojects_service.model.filter(
                name=project_in.name, 
                user_id=project_in.user_id,
                is_deleted=False
            ).first()
            if existing_project:
                raise BusinessError(RESOURCE_ALREADY_EXISTS.format(resource="AI项目"), details="该项目名称已存在")
            
            new_project = await aiprojects_service.create(project_in)
            return new_project
        except Exception as e:
            raise BusinessError(RESOURCE_CREATE_FAILED.format(resource="AI项目"), details=f"创建AI项目失败 {str(e)}")

    async def update_project_info(self, project_id: int, obj_in: AIProjectUpdate, user_id: int) -> bool:
        """更新AI项目信息"""
        try:
            project_obj = await aiprojects_service.get_project_by_user(project_id, user_id)
            if not project_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="AI项目"), details="项目不存在")
            await aiprojects_service.update(project_id, obj_in)
            return True
        except Exception as e:
            raise BusinessError(RESOURCE_UPDATE_FAILED.format(resource="AI项目"), details=f"更新AI项目失败 {str(e)}")

    async def increase_views(self, project_id: int, user_id: int) -> AIProject:
        """增加项目浏览量"""
        try:
            project_obj = await aiprojects_service.get_project_by_user(project_id, user_id)
            if not project_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="AI项目"), details="项目不存在")
            project_obj.views += 1
            await project_obj.save()
            return project_obj
        except Exception as e:
            raise BusinessError(OPERATION_FAILED.format(operation="增加浏览量"), details=f"增加浏览量失败 {str(e)}")

    async def toggle_star(self, project_id: int, user_id: int) -> AIProject:
        """收藏/取消收藏项目"""
        try:
            project_obj = await aiprojects_service.get_project_by_user(project_id, user_id)
            if not project_obj:
                raise BusinessError(RESOURCE_NOT_FOUND.format(resource="AI项目"), details="项目不存在")
            project_obj.stars = 1 if project_obj.stars == 0 else 0
            await project_obj.save()
            return project_obj
        except Exception as e:
            raise BusinessError(OPERATION_FAILED.format(operation="收藏操作"), details=f"收藏操作失败 {str(e)}")

ai_project_controller = AIProjectController()